<?php 
/*
 * Created on Feb 3, 2010
 *
 * To change the template for this generated file go to
 * Window - Preferences - PHPeclipse - PHP - Code Templates
 */
include ("ConnectDB_mysqli.php");
include ("form.php");
include ('MiscFunctions.php');

class Session {
    var $username; //Username given on sign-up
    var $userid; //Random value generated on current login
    var $userlevel; //The level to which the user pertains
    var $time; //Time user was last active (page loaded)
    var $logged_in; //True if user is logged in, false otherwise
    var $userinfo = array(); //The array holding all user info
    var $url; //The page url current being viewed
    var $referrer; //Last recorded site page viewed
    
    var $num_active_users; //Number of active users viewing site
    var $num_active_guests; //Number of active guests viewing site
    var $num_members; //Number of signed-up users
    /**
     * Note: referrer should really only be considered the actual
     * page referrer in process.php, any other time it may be
     * inaccurate.
     */
     
    /* Class constructor */
    function Session() {
        $this->time = time();
        
        $this->num_members = -1;
        
        if (TRACK_VISITORS) {
            /* Calculate number of users at site */
            $this->calcNumActiveUsers();
            
            /* Calculate number of guests at site */
            $this->calcNumActiveGuests();
        }
        
        $this->startSession();
    }
    
    function setHeader($headerBalue = null) {
        $_SESSION['CurrentHeader'] = $headerBalue;
    }
    
    function startSession() {
        global $connDB; //The database connection
        session_start(); //Tell PHP to start the session
        
        if (!isset($_SESSION['DefaultDateFormat'])) {
            $_SESSION['DefaultDateFormat'] = DEFAULT_DATE_FORMAT;
        }
		if (!isset($_SESSION['PathUploadContent'])) {
            $_SESSION['PathUploadContent'] = PATH_UPLOAD_CONTENT;
        }
		if (!isset($_SESSION['PathUploadItem'])) {
            $_SESSION['PathUploadItem'] = PATH_ITEM_IMAGE;
        }
		if (!isset($_SESSION['MaxFileUpload'])) {
            $_SESSION['MaxFileUpload'] = MAX_FILE_UPLOAD;
        }
		if (!isset($_SESSION['PathUploadBanner'])) {
            $_SESSION['PathUploadBanner'] = PATH_UPLOAD_BANNER;
        }
                
        /* Determine if user is logged in */
        $this->logged_in = $this->checkLogin();
        
        /**
         * Set guest value to users not logged in, and update
         * active guests table accordingly.
         */		
        if (!$this->logged_in) {
            $this->username = $_SESSION['username'] = GUEST_NAME;
            $this->userlevel = GUEST_LEVEL;
            $this->addActiveGuest($_SERVER['REMOTE_ADDR'], $this->time);
        }
        /* Update users last active timestamp */
        else {
        
            $this->addActiveUser($this->username, $this->time);
        }
        
        /* Remove inactive visitors from database */
        $this->removeInactiveUsers();
        $this->removeInactiveGuests();
        
        /* Set referrer page */
        if (isset($_SESSION['url'])) {
            $this->referrer = $_SESSION['url'];
        } else {
            $this->referrer = currentPageURL();
        }
        
        /* Set current url */
        $this->url = $_SESSION['url'] = currentPageURL();
        
    }
    
    function checkLogin() {
        global $connDB; //The database connection
        /* Check if user has been remembered */
        if (isset($_COOKIE['cookname']) && isset($_COOKIE['cookid'])) {
            $this->username = $_SESSION['username'] = $_COOKIE['cookname'];
            $this->userid = $_SESSION['userid'] = $_COOKIE['cookid'];
        }
        
        /* Username and userid have been set and not guest */
        if (isset($_SESSION['username']) && isset($_SESSION['userid']) && $_SESSION['username'] != GUEST_NAME) {
            /* Confirm that username and userid are valid */
            if ($this->confirmUserID($_SESSION['username'], $_SESSION['userid']) != 0) {
                /* Variables are incorrect, user not logged in */
                
                unset($_SESSION['username']);
                unset($_SESSION['userid']);
                return false;
            }
            
            /* User is logged in, set class variables */
            $this->userinfo = $this->getUserInfo($_SESSION['username']);
            $this->username = $this->userinfo['userName'];
            $this->userid = $this->userinfo['id'];
            $this->userlevel = $this->userinfo['userlevel'];
			
            return true;
        }
        /* User not logged in */
        else {
            return false;
        }
    }
    
    function confirmUserID($username, $userid) {
        global $connDB; //The database connection
        /* Add slashes if necessary (for query) */
        if (!get_magic_quotes_gpc()) {
            $username = addslashes($username);
        }
        
        /* Verify that user is in database */
        $sql = "SELECT id FROM ".TBL_USERS." WHERE userName = '$username'";
        
        $result = $connDB->DB_query($sql, $connDB->connection);
        
        if (!$result || ($connDB->DB_num_rows($result) < 1)) {
            return 1; //Indicates username failure
        }
        
        /* Retrieve userid from result, strip slashes */
        $dbarray = $connDB->DB_fetch_array($result);
        $dbarray['id'] = stripslashes($dbarray['id']);
        $userid = stripslashes($userid);
        
        /* Validate that userid is correct */
        if ($userid == $dbarray['id']) {
            return 0; //Success! Username and userid confirmed
        } else {
            return 2; //Indicates userid invalid
        }
    }
    
    function getUserInfo($username) {
        global $connDB; //The database connection
        $sql = "SELECT * FROM ".TBL_USERS." WHERE userName = '$username'";
        $result = $connDB->DB_query($sql, $connDB->connection);
        /* Error occurred, return given name by default */
        if (!$result || ($connDB->DB_num_rows($result) < 1)) {
            return NULL;
        }
        /* Return result array */
        $dbarray = $connDB->DB_fetch_array($result);
        return $dbarray;
    }
    
    function addActiveGuest($ip, $time) {
        global $connDB; //The database connection
        if (!TRACK_VISITORS)
            return;
        $sql = "REPLACE INTO ".TBL_ACTIVE_GUESTS." VALUES ('$ip', '$time')";
        $connDB->DB_query($sql, $connDB->connection);
        $this->calcNumActiveGuests();
    }
    
    function calcNumActiveGuests() {
        global $connDB; //The database connection
        /* Calculate number of guests at site */
        $sql = "SELECT * FROM ".TBL_ACTIVE_GUESTS;
        $result = $connDB->DB_query($sql, $connDB->connection);
        $this->num_active_guests = $connDB->DB_num_rows($result);
    }
    
    function addActiveUser($username, $time) {
        global $connDB; //The database connection
        $sql = "UPDATE ".TBL_USERS." SET lastLoginDate = '".date('Y-m-d h:m:s')."' WHERE userName = '$username'";
        $connDB->DB_query($sql, $connDB->connection);
        
        if (!TRACK_VISITORS)
            return;
        $sql = "REPLACE INTO ".TBL_ACTIVE_USERS." VALUES ('$username', '$time')";
        $connDB->DB_query($sql, $connDB->connection);
        $this->calcNumActiveUsers();
    }
    
    function calcNumActiveUsers() {
        global $connDB; //The database connection
        /* Calculate number of users at site */
        $sql = "SELECT * FROM ".TBL_ACTIVE_USERS;
        $result = $connDB->DB_query($sql, $connDB->connection);
        $this->num_active_users = $connDB->DB_num_rows($result);
    }
    
    /* removeInactiveUsers */
    function removeInactiveUsers() {
        global $connDB; //The database connection
        if (!TRACK_VISITORS)
            return;
        $timeout = time() - USER_TIMEOUT * 60;
        $sql = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE timestamp < $timeout";
        $connDB->DB_query($sql, $connDB->connection);
        $this->calcNumActiveUsers();
    }
    
    /* removeInactiveGuests */
    function removeInactiveGuests() {
        global $connDB; //The database connection
        if (!TRACK_VISITORS)
            return;
        $timeout = time() - GUEST_TIMEOUT * 60;
        $sql = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE timestamp < $timeout";
        $connDB->DB_query($sql, $connDB->connection);
        $this->calcNumActiveGuests();
    }
    
    /* removeActiveGuest */
    function removeActiveGuest($ip) {
        global $connDB; //The database connection
        if (!TRACK_VISITORS)
            return;
        $q = "DELETE FROM ".TBL_ACTIVE_GUESTS." WHERE ip = '$ip'";
        $connDB->DB_query($sql, $connDB->connection);
        $this->calcNumActiveGuests();
    }
    
    /* removeActiveUser */
    function removeActiveUser($username) {
        global $connDB; //The database connection
        if (!TRACK_VISITORS)
            return;
        $sql = "DELETE FROM ".TBL_ACTIVE_USERS." WHERE userName = '$username'";
        $connDB->DB_query($sql, $connDB->connection);
        $this->calcNumActiveUsers();
    }
}
;

$session = new Session;

/* Initialize form object */
$form = new Form;

?>